from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QLabel,
                             QLineEdit, QPushButton, QFileDialog, QGraphicsView, QGraphicsScene, QFrame)
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap
from core.image_processor.extract_frame import extract_frames
import os
import glob

class FrameExtractionPanel(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.preview_scale = 1.0
        self.current_project = None  # 新增当前项目属性
        self._init_ui()
        
    def _init_ui(self):
        layout = QVBoxLayout()
        
        # Video file selection
        video_layout = QHBoxLayout()
        self.video_path_edit = QLineEdit()
        self.video_path_edit.setPlaceholderText("视频文件路径")
        btn_browse_video = QPushButton("选择视频")
        btn_browse_video.clicked.connect(self.browse_video)
        video_layout.addWidget(QLabel("视频文件:"))
        video_layout.addWidget(self.video_path_edit)
        video_layout.addWidget(btn_browse_video)
        layout.addLayout(video_layout)
        
        # Output folder selection
        output_layout = QHBoxLayout()
        self.output_folder_edit = QLineEdit()
        self.output_folder_edit.setPlaceholderText("输出文件夹路径")
        btn_browse_output = QPushButton("选择文件夹")
        btn_browse_output.clicked.connect(self.browse_output)
        output_layout.addWidget(QLabel("输出文件夹:"))
        output_layout.addWidget(self.output_folder_edit)
        output_layout.addWidget(btn_browse_output)
        layout.addLayout(output_layout)
        
        # Extraction interval input
        interval_layout = QHBoxLayout()
        self.interval_edit = QLineEdit()
        self.interval_edit.setPlaceholderText("间隔秒数")
        self.interval_edit.setText("1.5")
        interval_layout.addWidget(QLabel("间隔(秒):"))
        interval_layout.addWidget(self.interval_edit)
        layout.addLayout(interval_layout)
        
        # Extraction button
        self.extract_button = QPushButton("抽帧")
        self.extract_button.clicked.connect(self.run_extraction)
        layout.addWidget(self.extract_button)
        
        # Preview area added for zoom functionality
        self.preview_scene = QGraphicsScene()
        self.preview_view = QGraphicsView(self.preview_scene)
        self.preview_view.setFrameShape(QFrame.NoFrame)
        self.preview_view.setDragMode(QGraphicsView.NoDrag)
        layout.addWidget(self.preview_view)
        
        # Status label for feedback
        self.status_label = QLabel("")
        layout.addWidget(self.status_label)
        
        self.setLayout(layout)
        
    def browse_video(self):
        path, _ = QFileDialog.getOpenFileName(self, "选择视频文件", "", "视频文件 (*.mp4 *.avi *.mov)")
        if path:
            self.video_path_edit.setText(path)
            
    def browse_output(self):
        folder = QFileDialog.getExistingDirectory(self, "选择输出文件夹")
        if folder:
            self.output_folder_edit.setText(folder)
            
    def set_project(self, project_path):
        self.current_project = project_path

    def run_extraction(self):
        video_path = self.video_path_edit.text().strip()
        output_dir = self.output_folder_edit.text().strip()
        try:
            interval_sec = float(self.interval_edit.text().strip())
        except ValueError:
            self.status_label.setText("请输入有效的间隔秒数.")
            return
        if not video_path:
            self.status_label.setText("请提供视频文件.")
            return
        # 若未选择输出文件夹且有当前项目，则默认输出到其 Videos 子文件夹。
        if not output_dir and self.current_project:
            output_dir = os.path.join(self.current_project, "Videos")
            self.output_folder_edit.setText(output_dir)
        if not output_dir:
            self.status_label.setText("请提供输出文件夹.")
            return
        try:
            extract_frames(video_path, output_dir, interval_sec=interval_sec)
            self.status_label.setText("抽帧完成!")
            frames = sorted(glob.glob(os.path.join(output_dir, "*.jpg")))
            if frames:
                self.load_preview(frames[0])
        except Exception as e:
            self.status_label.setText(f"抽帧出错: {e}")
            
    def load_preview(self, image_path):
        self.preview_scene.clear()
        self.original_preview = QPixmap(image_path)  # save original preview pixmap
        self.update_preview_display()
        self.preview_scale = 1.0

    def update_preview_display(self):
        if hasattr(self, 'original_preview'):
            w = int(self.original_preview.width() * self.preview_scale)
            h = int(self.original_preview.height() * self.preview_scale)
            scaled = self.original_preview.scaled(w, h, Qt.KeepAspectRatio, Qt.SmoothTransformation)
            # Clear scene and add scaled pixmap.
            self.preview_scene.clear()
            self.preview_scene.addPixmap(scaled)
            self.preview_view.fitInView(self.preview_scene.itemsBoundingRect(), Qt.KeepAspectRatio)

    def zoom_in(self):
        self.preview_scale *= 1.25
        self.update_preview_display()
        
    def zoom_out(self):
        self.preview_scale /= 1.25
        self.update_preview_display()

